package com.bootcamp.javase2.threads;

import com.sun.corba.se.impl.resolver.FileResolverImpl;

import java.io.*;
import java.text.DecimalFormat;

/**
 * @program: ThreadCode
 * @description: copy a file with multi threads
 * @author: Keyu Li
 * @create: 2021-09-13 19:27
 **/

public class ThreadCopy {
    static final String SRC_FILR = "D:/wd/copythreads/jiyu.exe";
    static final String DST_DIR = "D:/wd/copythreads/";
    static final int THREAD_NUM = 5;

    public static void main(String[] args) throws IOException {
        // get src file size
        File srcFile = new File(SRC_FILR);
        double srcSize = srcFile.length() * 1.0 / (1 << 20);
        System.out.println("file " + srcFile.getName() + " size is "
                + new DecimalFormat("#.00").format(srcSize) + " MB");

        // get dst file name
        String[] dst = new String[THREAD_NUM];
        for (int i = 0; i < THREAD_NUM; i++) {
            dst[i] = SRC_FILR.replace(".exe", "_") + i + ".exe";
        }
        // create thread
        for (int i = 0; i < THREAD_NUM; i++) {
            new FileCopyThread("Thread"+i, srcFile, dst[i], srcSize).start();
        }
    }
}

class FileCopyThread extends Thread {
    FileInputStream in;
    FileOutputStream out;
    byte[] bytes = new byte[1 << 20];
    double totalSize;


    public FileCopyThread(String name, File src, String dst,
                          double totalSize) throws FileNotFoundException {
        super(name);
        in = new FileInputStream(src);
        out = new FileOutputStream(dst);
        this.totalSize = totalSize;
    }

    @Override
    public void run() {
        int count = 0;
        int flag = -1;
        try {
            while ((flag = in.read(bytes)) != -1) {
                out.write(bytes);
                count++;
                if (count >= totalSize) break;
                System.out.println(this.getName()
                        + " has already copied [ " + count + " MB "
                        + new DecimalFormat("#.00").
                        format(count*100 / totalSize)
                        + "% ]");
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(this.getName()+" Copy success!");
    }
}
